from flask import Flask, render_template, request, jsonify
import serial
import time
import threading
import json
import sqlite3
from datetime import datetime, timedelta
import numpy as np
import joblib
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB

app = Flask(__name__)

# 串口设置
ser = None
simulation_mode = False

# 尝试连接Arduino
for port in ['COM3', 'COM4', 'COM5', 'COM6', '/dev/ttyACM0', '/dev/ttyUSB0']:
    try:
        ser = serial.Serial(port, 9600, timeout=1)
        print(f"成功连接到Arduino: {port}")
        time.sleep(2)  # 等待Arduino初始化
        break
    except Exception as e:
        print(f"无法连接到{port}: {e}")

# 如果没有连接到Arduino，使用模拟模式
if ser is None:
    print("无法连接到Arduino，启用模拟模式")
    simulation_mode = True

# 初始化数据库
def init_db():
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    
    # 创建设备状态记录表格
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS device_states (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id INTEGER,
        state INTEGER,
        timestamp TEXT
    )
    ''')
    
    # 创建环境数据记录表格
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS environment_data (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        temperature1 REAL,
        temperature2 REAL,
        humidity1 REAL,
        humidity2 REAL,
        current1 REAL,
        current2 REAL,
        current3 REAL,
        current4 REAL,
        timestamp TEXT
    )
    ''')
    
    # 创建用电记录表格
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS energy_usage (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id INTEGER,
        usage_kwh REAL,
        date TEXT
    )
    ''')
    
    # 创建定时任务表格
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS schedules (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id INTEGER,
        action INTEGER,
        time TEXT,
        days TEXT,
        enabled INTEGER
    )
    ''')
    
    # 创建使用模式表格
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS usage_patterns (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id INTEGER,
        hour INTEGER,
        day INTEGER,
        is_used INTEGER,
        timestamp TEXT
    )
    ''')
    
    conn.commit()
    conn.close()

# 初始化数据库
exit_if_error = False
try:
    init_db()
except Exception as e:
    print(f"数据库初始化错误: {e}")
    exit_if_error = True

# 如果数据库初始化失败，需要处理
if exit_if_error:
    # 尝试创建一个简单的数据库
    try:
        conn = sqlite3.connect('smart_home.db')
        conn.close()
        print("成功创建数据库文件")
        init_db()
    except Exception as e:
        print(f"创建数据库文件失败: {e}")
        # 在实际应用中，可能需要退出程序或使用备用方案

# 系统状态
system_status = {
    'relays': [False] * 8,  # 8路继电器状态
    'temperatures': [25.0, 25.0],  # 两个温度传感器
    'humidities': [50.0, 50.0],  # 两个湿度传感器
    'currents': [0.0, 0.0, 0.0, 0.0],  # 四个电流传感器
    'last_update': time.time()
}

# 设备配置
device_config = [
    {'id': 1, 'name': '主灯', 'type': 'lighting', 'icon': 'lightbulb', 'room': '客厅'},
    {'id': 2, 'name': '空调', 'type': 'air_conditioner', 'icon': 'temperature-high', 'room': '客厅'},
    {'id': 3, 'name': '风扇', 'type': 'fan', 'icon': 'fan', 'room': '卧室'},
    {'id': 4, 'name': '电视', 'type': 'entertainment', 'icon': 'tv', 'room': '客厅'},
    {'id': 5, 'name': '加湿器', 'type': 'appliance', 'icon': 'droplet', 'room': '卧室'},
    {'id': 6, 'name': '空气净化器', 'type': 'appliance', 'icon': 'wind', 'room': '卧室'},
    {'id': 7, 'name': '厨房灯', 'type': 'lighting', 'icon': 'lightbulb', 'room': '厨房'},
    {'id': 8, 'name': '音响', 'type': 'entertainment', 'icon': 'music', 'room': '客厅'}
]

# 场景配置
scene_config = [
    {'id': 1, 'name': '回家模式', 'icon': 'home', 'description': '打开主灯和空调'},
    {'id': 2, 'name': '睡眠模式', 'icon': 'moon', 'description': '关闭主灯，打开风扇和加湿器'},
    {'id': 3, 'name': '离家模式', 'icon': 'sign-out-alt', 'description': '关闭所有设备'},
    {'id': 4, 'name': '观影模式', 'icon': 'film', 'description': '关闭主灯，打开电视和音响'}
]

# AI使用模式分析模块
class UsagePatternAnalyzer:
    def __init__(self):
        self.models = {}
        # 加载或创建模型
        try:
            for i in range(1, 9):  # 8个设备
                try:
                    self.models[i] = joblib.load(f'model_device_{i}.pkl')
                except:
                    pass  # 如果模型不存在，先不加载
        except:
            pass  # 忽略加载模型的错误
    
    def train_model(self, device_id):
        try:
            conn = sqlite3.connect('smart_home.db')
            cursor = conn.cursor()
            
            # 获取设备的使用模式数据
            cursor.execute(
                "SELECT hour, day, is_used FROM usage_patterns WHERE device_id = ?",
                (device_id,)
            )
            data = cursor.fetchall()
            conn.close()
            
            if len(data) < 50:  # 数据量不足
                return None
            
            # 准备训练数据
            X = np.array([[row[0], row[1]] for row in data])
            y = np.array([row[2] for row in data])
            
            # 训练模型
            model = GaussianNB()
            model.fit(X, y)
            
            # 保存模型
            try:
                joblib.dump(model, f'model_device_{device_id}.pkl')
                self.models[device_id] = model
            except:
                print(f"无法保存模型到文件，但模型已训练成功")
            
            return model
        except Exception as e:
            print(f"训练模型错误: {e}")
            return None
    
    def predict_usage(self, device_id, hour, day):
        # 如果没有训练好的模型，返回默认概率
        if device_id not in self.models:
            try:
                # 尝试从数据库统计概率
                conn = sqlite3.connect('smart_home.db')
                cursor = conn.cursor()
                
                # 计算特定小时和星期几的使用概率
                cursor.execute(
                    "SELECT COUNT(*) FROM usage_patterns WHERE device_id = ? AND hour = ? AND day = ? AND is_used = 1",
                    (device_id, hour, day)
                )
                used_count = cursor.fetchone()[0]
                
                cursor.execute(
                    "SELECT COUNT(*) FROM usage_patterns WHERE device_id = ? AND hour = ? AND day = ?",
                    (device_id, hour, day)
                )
                total_count = cursor.fetchone()[0]
                
                conn.close()
                
                if total_count > 0:
                    return used_count / total_count
            except:
                pass  # 忽略数据库查询错误
            return 0.5  # 默认概率
        
        # 使用模型预测
        try:
            return self.models[device_id].predict_proba([[hour, day]])[0][1]
        except:
            return 0.5  # 预测错误时返回默认概率
    
    def get_smart_suggestions(self):
        # 基于当前时间和使用模式生成智能建议
        now = datetime.now()
        current_hour = now.hour
        current_day = now.weekday()
        
        suggestions = []
        
        # 检查每个设备
        for device in device_config:
            device_id = device['id']
            current_state = system_status['relays'][device_id - 1]
            
            # 获取预测概率
            prob = self.predict_usage(device_id, current_hour, current_day)
            
            # 如果预测应该开启但当前关闭，或者预测应该关闭但当前开启
            if (prob > 0.7 and not current_state) or (prob < 0.3 and current_state):
                action = "开启" if prob > 0.7 else "关闭"
                confidence = prob if prob > 0.7 else 1 - prob
                
                suggestions.append({
                    'device_id': device_id,
                    'device_name': device['name'],
                    'suggested_action': action,
                    'confidence': round(confidence * 100),
                    'reason': f"基于您的使用习惯，此时{action}{device['name']}的概率较高"
                })
        
        return suggestions

# 创建使用模式分析器实例
usage_analyzer = UsagePatternAnalyzer()

# 模拟数据
if simulation_mode:
    simulated_data = {
        'relays': [False] * 8,
        'temperatures': [25.5, 24.8],
        'humidities': [48.2, 51.5],
        'currents': [0.0, 0.0, 0.0, 0.0]
    }
    
    # 模拟模式下的模拟标签数据
    simulated_tags = [
        {'tag_id': 'TAG001', 'action': 'ON', 'device_id': 1},
        {'tag_id': 'TAG002', 'action': 'OFF', 'device_id': 1},
        {'tag_id': 'TAG003', 'action': 'ON', 'device_id': 2},
        {'tag_id': 'TAG004', 'action': 'OFF', 'device_id': 2},
        {'tag_id': 'TAG005', 'action': 'SCENE', 'scene_id': 1}
    ]
    
    # 模拟模式下的模式切换数据
    simulated_mode_switches = [
        {'time': '08:00', 'action': '回家模式'},
        {'time': '12:00', 'action': '离家模式'},
        {'time': '18:00', 'action': '回家模式'},
        {'time': '22:30', 'action': '睡眠模式'}
    ]

# 处理Arduino发送的数据
def process_arduino_data(data):
    try:
        # 解析JSON数据
        data = data.strip()
        if data.startswith('{') and data.endswith('}'):
            parsed_data = json.loads(data)
            
            # 更新系统状态
            if 'relays' in parsed_data:
                system_status['relays'] = [bool(int(x)) for x in parsed_data['relays']]
            
            if 'temperatures' in parsed_data:
                system_status['temperatures'] = [float(x) for x in parsed_data['temperatures']]
            
            if 'humidities' in parsed_data:
                system_status['humidities'] = [float(x) for x in parsed_data['humidities']]
            
            if 'currents' in parsed_data:
                system_status['currents'] = [float(x) for x in parsed_data['currents']]
            
            system_status['last_update'] = time.time()
            
            # 存储数据到数据库
            store_data_to_db(parsed_data)
            
    except Exception as e:
        print(f"处理Arduino数据错误: {e}")

# 存储数据到数据库
def store_data_to_db(data):
    try:
        conn = sqlite3.connect('smart_home.db')
        cursor = conn.cursor()
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
        
        # 存储环境数据
        cursor.execute(
            "INSERT INTO environment_data (temperature1, temperature2, humidity1, humidity2, current1, current2, current3, current4, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (data['temperatures'][0], data['temperatures'][1],
             data['humidities'][0], data['humidities'][1],
             data['currents'][0], data['currents'][1], data['currents'][2], data['currents'][3],
             timestamp)
        )
        
        # 存储设备状态变化
        for i, state in enumerate(data['relays']):
            device_id = i + 1
            # 检查状态是否变化（简化版，实际应该比较前一次状态）
            cursor.execute(
                "INSERT INTO device_states (device_id, state, timestamp) VALUES (?, ?, ?)",
                (device_id, int(state), timestamp)
            )
            
            # 记录使用模式
            hour = datetime.now().hour
            day = datetime.now().weekday()
            cursor.execute(
                "INSERT INTO usage_patterns (device_id, hour, day, is_used, timestamp) VALUES (?, ?, ?, ?, ?)",
                (device_id, hour, day, int(state), timestamp)
            )
        
        # 计算并存储用电量
        voltage = 220.0  # 假设电压为220V
        for i, current in enumerate(data['currents']):
            device_id = i + 1
            power = voltage * current  # 功率 = 电压 * 电流
            energy_kwh = power / 1000 * (5 / 3600)  # 5秒用电量，转换为kWh
            
            if energy_kwh > 0:
                date = time.strftime('%Y-%m-%d')
                # 检查当天是否已有记录
                cursor.execute(
                    "SELECT usage_kwh FROM energy_usage WHERE device_id = ? AND date = ?",
                    (device_id, date)
                )
                result = cursor.fetchone()
                
                if result:
                    # 更新现有记录
                    new_usage = result[0] + energy_kwh
                    cursor.execute(
                        "UPDATE energy_usage SET usage_kwh = ? WHERE device_id = ? AND date = ?",
                        (new_usage, device_id, date)
                    )
                else:
                    # 创建新记录
                    cursor.execute(
                        "INSERT INTO energy_usage (device_id, usage_kwh, date) VALUES (?, ?, ?)",
                        (device_id, energy_kwh, date)
                    )
        
        conn.commit()
        conn.close()
        
    except Exception as e:
        print(f"存储数据到数据库错误: {e}")

# 发送命令到Arduino
def send_command_to_arduino(command):
    try:
        if ser and ser.is_open:
            ser.write(f"{command}\n".encode('utf-8'))
            print(f"发送命令: {command}")
            return True
        return False
    except Exception as e:
        print(f"发送命令错误: {e}")
        return False

# 数据接收线程
def data_receive_thread():
    simulated_counter = 0
    while True:
        try:
            if ser and ser.is_open:
                if ser.in_waiting > 0:
                    line = ser.readline().decode('utf-8').strip()
                    if line:
                        process_arduino_data(line)
            elif simulation_mode:
                # 模拟模式：每5秒生成一次数据
                simulated_counter += 1
                if simulated_counter >= 50:  # 5秒 (每次循环0.1秒)
                    simulated_counter = 0
                    
                    # 随机生成一些数据变化
                    import random
                    
                    # 每5次迭代切换一次模式
                    if random.random() < 0.2:
                        # 随机选择一个模式切换
                        if random.random() < 0.5:
                            # 随机选择一个设备切换状态
                            device_id = random.randint(1, 8)
                            state = random.choice([True, False])
                            system_status['relays'][device_id - 1] = state
                            print(f"模拟模式: 设备 {device_id} {'开启' if state else '关闭'}")
                        else:
                            # 随机调整温度和湿度
                            system_status['temperatures'][0] += random.uniform(-0.2, 0.2)
                            system_status['temperatures'][1] += random.uniform(-0.2, 0.2)
                            system_status['humidities'][0] += random.uniform(-0.5, 0.5)
                            system_status['humidities'][1] += random.uniform(-0.5, 0.5)
                            
                            # 限制范围
                            system_status['temperatures'] = [max(10, min(40, t)) for t in system_status['temperatures']]
                            system_status['humidities'] = [max(20, min(90, h)) for h in system_status['humidities']]
                        
                    # 更新电流值（基于设备状态）
                    system_status['currents'] = [0.0] * 4
                    for i, state in enumerate(system_status['relays']):
                        if state:
                            # 为开启的设备分配电流
                            current_idx = i % 4
                            system_status['currents'][current_idx] += random.uniform(0.1, 2.0) if i < 4 else random.uniform(0.1, 1.0)
                    
                    system_status['last_update'] = time.time()
                    
                    # 构造模拟数据并存储
                    simulated_data = {
                        'relays': system_status['relays'],
                        'temperatures': system_status['temperatures'],
                        'humidities': system_status['humidities'],
                        'currents': system_status['currents']
                    }
                    
                    # 处理模拟数据，就像处理Arduino数据一样
                    store_data_to_db(simulated_data)
                        
            time.sleep(0.1)
            
        except Exception as e:
            print(f"数据接收线程错误: {e}")
            time.sleep(1)

# 启动数据接收线程
threading.Thread(target=data_receive_thread, daemon=True).start()

# 定时任务执行线程
def schedule_execution_thread():
    while True:
        try:
            now = datetime.now()
            current_time = now.strftime('%H:%M')
            current_day = now.weekday()
            
            # 检查是否有需要执行的定时任务
            conn = sqlite3.connect('smart_home.db')
            cursor = conn.cursor()
            
            # 获取所有启用的定时任务
            cursor.execute("SELECT id, device_id, action, time, days FROM schedules WHERE enabled = 1")
            schedules = cursor.fetchall()
            
            for schedule in schedules:
                schedule_id, device_id, action, scheduled_time, days = schedule
                
                # 检查时间是否匹配
                if scheduled_time == current_time:
                    # 检查星期几是否匹配
                    days_list = days.split(',')
                    if str(current_day) in days_list or days == '*':
                        # 执行任务
                        command = f"RELAY{device_id}:{'ON' if action == 1 else 'OFF'}"
                        send_command_to_arduino(command)
                        
                        # 记录任务执行
                        print(f"执行定时任务 #{schedule_id}: {command}")
            
            conn.close()
            
            # 每分钟检查一次
            time.sleep(60)
            
        except Exception as e:
            print(f"定时任务线程错误: {e}")
            time.sleep(10)

# 启动定时任务线程
threading.Thread(target=schedule_execution_thread, daemon=True).start()

# Web路由
@app.route('/')
def index():
    # 获取智能建议
    smart_suggestions = usage_analyzer.get_smart_suggestions()
    
    # 获取房间列表
    rooms = list(set([device['room'] for device in device_config]))
    rooms.sort()
    
    # 计算当前总功耗
    voltage = 220.0  # 假设电压为220V
    total_power = sum([current * voltage for current in system_status['currents']]) / 1000  # kW
    
    return render_template('index.html', 
                          system_status=system_status, 
                          device_config=device_config,
                          scene_config=scene_config,
                          smart_suggestions=smart_suggestions,
                          rooms=rooms,
                          total_power=round(total_power, 2))

@app.route('/devices')
def devices():
    return render_template('devices.html', 
                          system_status=system_status, 
                          device_config=device_config)

@app.route('/rooms/<room>')
def room_devices(room):
    # 获取特定房间的设备
    room_devices = [device for device in device_config if device['room'] == room]
    
    return render_template('room_devices.html', 
                          room=room, 
                          devices=room_devices,
                          system_status=system_status)

@app.route('/scenes')
def scenes():
    return render_template('scenes.html', scene_config=scene_config)

@app.route('/analytics')
def analytics():
    return render_template('analytics.html')

@app.route('/schedules')
def schedules():
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM schedules")
    schedules = cursor.fetchall()
    conn.close()
    
    # 将设备ID转换为设备名称
    schedule_list = []
    device_map = {device['id']: device['name'] for device in device_config}
    
    for schedule in schedules:
        schedule_list.append({
            'id': schedule[0],
            'device_id': schedule[1],
            'device_name': device_map.get(schedule[1], '未知设备'),
            'action': '开启' if schedule[2] == 1 else '关闭',
            'time': schedule[3],
            'days': schedule[4],
            'enabled': schedule[5]
        })
    
    return render_template('schedules.html', schedules=schedule_list)

@app.route('/api/toggle_relay', methods=['POST'])
def toggle_relay():
    data = request.json
    device_id = data['device_id']
    state = data['state']
    
    # 发送命令到Arduino
    command = f"RELAY{device_id}:{'ON' if state else 'OFF'}"
    success = send_command_to_arduino(command)
    
    # 在模拟模式下，直接更新状态
    if simulation_mode:
        system_status['relays'][device_id - 1] = state
        success = True
    
    if success:
        return jsonify({'success': True})
    else:
        return jsonify({'success': False, 'message': '发送命令失败'})

@app.route('/api/activate_scene', methods=['POST'])
def activate_scene():
    data = request.json
    scene_id = data['scene_id']
    
    # 根据场景ID执行相应的操作
    if scene_id == 1:  # 回家模式
        commands = [
            "RELAY1:ON",  # 打开主灯
            "RELAY2:ON"   # 打开空调
        ]
    elif scene_id == 2:  # 睡眠模式
        commands = [
            "RELAY1:OFF",  # 关闭主灯
            "RELAY3:ON",   # 打开风扇
            "RELAY5:ON"    # 打开加湿器
        ]
    elif scene_id == 3:  # 离家模式
        commands = [f"RELAY{i}:OFF" for i in range(1, 9)]
    elif scene_id == 4:  # 观影模式
        commands = [
            "RELAY1:OFF",  # 关闭主灯
            "RELAY4:ON",   # 打开电视
            "RELAY8:ON"    # 打开音响
        ]
    else:
        return jsonify({'success': False, 'message': '无效的场景ID'})
    
    # 发送命令
    success = True
    for command in commands:
        if not send_command_to_arduino(command):
            success = False
        time.sleep(0.1)
    
    # 在模拟模式下，直接更新状态
    if simulation_mode:
        success = True
        # 解析命令并更新状态
        for command in commands:
            parts = command.split(':')
            if len(parts) == 2 and parts[0].startswith('RELAY'):
                try:
                    device_id = int(parts[0][5:])
                    state = parts[1] == 'ON'
                    if 1 <= device_id <= 8:
                        system_status['relays'][device_id - 1] = state
                except:
                    pass
    
    return jsonify({'success': success})

@app.route('/api/get_status')
def get_status():
    return jsonify(system_status)

@app.route('/api/add_schedule', methods=['POST'])
def add_schedule():
    data = request.json
    
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    
    try:
        cursor.execute(
            "INSERT INTO schedules (device_id, action, time, days, enabled) VALUES (?, ?, ?, ?, ?)",
            (data['device_id'], 1 if data['action'] == 'ON' else 0, data['time'], data['days'], 1)
        )
        conn.commit()
        conn.close()
        
        return jsonify({'success': True})
    except Exception as e:
        conn.close()
        return jsonify({'success': False, 'message': str(e)})

@app.route('/api/toggle_schedule', methods=['POST'])
def toggle_schedule():
    data = request.json
    schedule_id = data['schedule_id']
    enabled = data['enabled']
    
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    
    try:
        cursor.execute("UPDATE schedules SET enabled = ? WHERE id = ?", (1 if enabled else 0, schedule_id))
        conn.commit()
        conn.close()
        
        return jsonify({'success': True})
    except Exception as e:
        conn.close()
        return jsonify({'success': False, 'message': str(e)})

@app.route('/api/get_energy_data')
def get_energy_data():
    # 获取最近7天的用电数据
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    
    # 获取日期列表
    dates = []
    for i in range(7):
        date = (datetime.now() - timedelta(days=6 - i)).strftime('%Y-%m-%d')
        dates.append(date)
    
    # 获取每个设备的用电数据
    energy_data = {}
    for device in device_config:
        device_id = device['id']
        usage_data = []
        
        for date in dates:
            cursor.execute(
                "SELECT usage_kwh FROM energy_usage WHERE device_id = ? AND date = ?",
                (device_id, date)
            )
            result = cursor.fetchone()
            usage_data.append(result[0] if result else 0.0)
        
        energy_data[device['name']] = usage_data
    
    conn.close()
    
    # 如果没有数据（模拟环境），生成一些随机数据
    if all(all(value == 0 for value in values) for values in energy_data.values()):
        import random
        for device_name in energy_data:
            energy_data[device_name] = [random.uniform(0.1, 3.0) for _ in range(7)]
    
    # 格式化日期为显示格式
    display_dates = [datetime.strptime(date, '%Y-%m-%d').strftime('%m-%d') for date in dates]
    
    return jsonify({
        'dates': display_dates,
        'energy_data': energy_data
    })

@app.route('/api/get_environment_data')
def get_environment_data():
    # 获取最近24小时的环境数据
    conn = sqlite3.connect('smart_home.db')
    cursor = conn.cursor()
    
    # 获取过去24小时的数据点（每小时一个）
    hours = []
    temps1 = []
    temps2 = []
    hums1 = []
    hums2 = []
    
    for i in range(24):
        hour_ago = datetime.now() - timedelta(hours=i)
        hour_str = hour_ago.strftime('%Y-%m-%d %H')
        
        # 查询该小时的平均数据
        cursor.execute(
            "SELECT AVG(temperature1), AVG(temperature2), AVG(humidity1), AVG(humidity2) FROM environment_data WHERE timestamp LIKE ?",
            (f"{hour_str}%",)
        )
        result = cursor.fetchone()
        
        if result and result[0] is not None:
            hours.append(hour_ago.strftime('%H:00'))
            temps1.append(round(result[0], 1))
            temps2.append(round(result[1], 1))
            hums1.append(round(result[2], 1))
            hums2.append(round(result[3], 1))
    
    conn.close()
    
    # 如果没有数据（模拟环境），生成一些随机数据
    if not hours:
        import random
        base_temp1, base_temp2 = 25.0, 24.5
        base_hum1, base_hum2 = 50.0, 52.0
        
        for i in range(24):
            hour = (datetime.now() - timedelta(hours=23 - i)).strftime('%H:00')
            hours.append(hour)
            # 添加一些基于时间的变化趋势
            time_factor = (i - 12) / 12  # -1 到 1
            
            temps1.append(round(base_temp1 + time_factor * 2 + random.uniform(-0.5, 0.5), 1))
            temps2.append(round(base_temp2 + time_factor * 1.5 + random.uniform(-0.5, 0.5), 1))
            hums1.append(round(base_hum1 - time_factor * 3 + random.uniform(-1.0, 1.0), 1))
            hums2.append(round(base_hum2 - time_factor * 2 + random.uniform(-1.0, 1.0), 1))
    else:
        # 反转顺序，从最早到最新
        hours.reverse()
        temps1.reverse()
        temps2.reverse()
        hums1.reverse()
        hums2.reverse()
    
    return jsonify({
        'hours': hours,
        'temperature1': temps1,
        'temperature2': temps2,
        'humidity1': hums1,
        'humidity2': hums2
    })

@app.route('/api/train_usage_model', methods=['POST'])
def train_usage_model():
    data = request.json
    device_id = data['device_id']
    
    # 训练模型
    model = usage_analyzer.train_model(device_id)
    
    if model:
        return jsonify({'success': True, 'message': '模型训练成功'})
    else:
        return jsonify({'success': False, 'message': '数据量不足，无法训练模型'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')